#include "head.h"

mqd_t msqid;
char * name;
mqd_t msqid_client;
mqd_t clients[32];
int client_count;

void sigint(int signo) {
	if (mq_close(msqid) == -1 ||mq_unlink(name) == -1) {
		free(name);
		perror("mqclose server");
		exit(1);
	} else {
		printf("Zamykanie kolejki\n");
		free(name);
		return;
	}
}

int main(int argc, char ** argv) {
	if (argc != 2) {
		printf("Złe wywołanie. Poprawne wywołanie: ./zad1a.o <path>\n");
		return 1;
	}
	if (signal(SIGINT, sigint) == SIG_ERR) {
		perror("signal server");
		return -1;
	}
	name = (char *)malloc(sizeof(char)*128);
	sprintf(name, "/%s", argv[1]);
	name[strlen(name)+1] = '\0';
	printf("%s\n", name);
	struct mq_attr attr;
	attr.mq_flags = 0;
	attr.mq_maxmsg = 10;
	attr.mq_msgsize = sizeof(struct message);
	if ((msqid = mq_open(name, O_CREAT | O_RDONLY, 0666, &attr)) == -1) {
		perror("mq_open server");
		return -2;
	}
	struct message cl_mess;
	while (1) {
		if (mq_receive(msqid, (char *)&cl_mess, sizeof(struct message), NULL) == -1) {
			perror("mq_recieve server");
			return -3;
		}
		if(cl_mess.type == 1) {
			if ((clients[client_count++] = mq_open(cl_mess.msg, O_WRONLY)) == -1) {
				perror("kolejka klienta mq_open");
				client_count--;
			} else {
				printf("Dodaje klienta %s\n", cl_mess.name);
			}
		} else if (cl_mess.type == 2){
			int i;
			for (i = 0; i < client_count; i++) {
				if (mq_send(clients[i], (char *)&cl_mess, sizeof(struct message), 0) == -1) {
					perror("mq_send");
				}
			}
		}
		sleep(1);
	}
	return 0;
}
